package com.xyy.controller;

import com.xyy.common.Result;
import com.xyy.dto.DoctorRegisterDTO;
import com.xyy.entity.Doctor;
import com.xyy.service.DoctorService;
import com.xyy.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 医生控制器
 */
@Slf4j
@RestController
@RequestMapping("/doctor")
@Validated
public class DoctorController {

    @Autowired
    private DoctorService doctorService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 医生注册
     */
    @PostMapping("/register")
    public Result<Map<String, Object>> register(@Valid @RequestBody DoctorRegisterDTO registerDTO) {
        try {
            // 将DTO转换为实体
            Doctor doctor = new Doctor();
            doctor.setUsername(registerDTO.getUsername());
            doctor.setPassword(registerDTO.getPassword());
            doctor.setRealName(registerDTO.getRealName());
            doctor.setGender(registerDTO.getGender());
            doctor.setPhone(registerDTO.getPhone());
            doctor.setEmail(registerDTO.getEmail());
            doctor.setAddress(registerDTO.getAddress());
            doctor.setPracticeScope(registerDTO.getPracticeScope());
            doctor.setHospitalName(registerDTO.getHospitalName());
            
            // 注册医生
            Map<String, Object> result = doctorService.register(doctor);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("医生注册失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 医生登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@Valid @RequestBody Doctor doctor) {
        try {
            // 登录医生
            Map<String, Object> result = doctorService.login(doctor);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("医生登录失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 发送邮箱验证码
     */
    @PostMapping("/sendEmailCode")
    public Result<Void> sendEmailCode(@RequestBody Map<String, String> requestData) {
        try {
            String email = requestData.get("email");
            String username = requestData.get("username"); // 可选
            
            if (email == null) {
                return Result.error("邮箱不能为空");
            }
            
            doctorService.sendEmailCode(email, username);
            return Result.success();
        } catch (Exception e) {
            log.error("发送邮箱验证码失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 密码重置
     */
    @PostMapping("/resetPassword")
    public Result<Void> resetPassword(@Valid @RequestBody Doctor doctor) {
        try {
            doctorService.resetPassword(doctor);
            return Result.success();
        } catch (Exception e) {
            log.error("密码重置失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取医生信息
     */
    @GetMapping("/info")
    public Result<Doctor> getDoctorInfo(HttpServletRequest request) {
        try {
            // 从token中获取医生ID
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long doctorId = jwtUtil.getUserIdFromToken(token);
            if (doctorId == null) {
                return Result.error("无效的token");
            }
            
            Doctor doctor = doctorService.getById(doctorId);
            if (doctor == null) {
                return Result.error("医生不存在");
            }
            
            return Result.success(doctor);
        } catch (Exception e) {
            log.error("获取医生信息失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

//    /**
//     * 根据用户名获取医生信息（密码找回用）
//     */
//    @GetMapping("/getDoctorInfoForReset")
//    public Result<Doctor> getDoctorInfoForReset(@RequestParam String username) {
//        try {
//            Doctor doctor = doctorService.getDoctorInfoForReset(username);
//            return Result.success(doctor);
//        } catch (Exception e) {
//            log.error("获取医生信息失败: {}", e.getMessage());
//            return Result.error(e.getMessage());
//        }
//    }

    /**
     * 根据用户名获取邮箱（密码找回用）
     */
    @GetMapping("/getEmailByUsername")
    public Result<Map<String, String>> getEmailByUsername(@RequestParam String username) {
        try {
            String email = doctorService.getEmailByUsername(username);
            Map<String, String> result = new HashMap<>();
            result.put("email", email);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取邮箱失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 验证邮箱验证码
     */
    @PostMapping("/verifyEmailCode")
    public Result<Void> verifyEmailCode(@RequestBody Map<String, String> requestData) {
        try {
            String username = requestData.get("username");
            String email = requestData.get("email");
            String emailCode = requestData.get("emailCode");
            
            if (username == null || email == null || emailCode == null) {
                return Result.error("用户名、邮箱和验证码不能为空");
            }
            
            boolean isValid = doctorService.verifyEmailCode(username, email, emailCode);
            if (isValid) {
                return Result.success();
            } else {
                return Result.error("验证码错误或已过期");
            }
        } catch (Exception e) {
            log.error("验证邮箱验证码失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 上传头像
     */
    @PostMapping("/uploadAvatar")
    public Result<Map<String, String>> uploadAvatar(@RequestParam("avatar") MultipartFile file,
                                                   HttpServletRequest request) {
        try {
            // 从token中获取医生ID
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long doctorId = jwtUtil.getUserIdFromToken(token);
            if (doctorId == null) {
                return Result.error("无效的token");
            }
            
            // 验证文件
            if (file.isEmpty()) {
                return Result.error("请选择要上传的文件");
            }
            
            // 验证文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || !isValidImageFile(originalFilename)) {
                return Result.error("只支持jpg, jpeg, png, gif, bmp格式的图片");
            }
            
            // 验证文件大小（5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return Result.error("文件大小不能超过5MB");
            }
            
            // 上传头像
            String avatarUrl = doctorService.uploadAvatar(doctorId, originalFilename, file.getBytes());
            
            Map<String, String> result = new HashMap<>();
            result.put("avatarUrl", avatarUrl);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("头像上传失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取所有医院名称列表（用于医生注册时选择）
     */
    @GetMapping("/hospitals")
    public Result<Map<String, Object>> getAllHospitals() {
        try {
            List<String> hospitals = doctorService.getAllHospitalNames();
            Map<String, Object> result = new HashMap<>();
            result.put("hospitals", hospitals);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取医院列表失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 验证图片文件类型
     */
    private boolean isValidImageFile(String filename) {
        String extension = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
        return extension.matches("(jpg|jpeg|png|gif|bmp)");
    }
} 

 